package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import ModelLayer.Product;

public class DBProduct implements IFDBProduct {
	
	private Connection con;
	
	 public DBProduct() {
	      con = DBConnection.getInstance().getDBcon();
	    }

	@Override
	public ArrayList<Product> getAll(boolean retriveAssociation) {
		
		return miscWhere("", retriveAssociation);
		
	}

	@Override
	public Product findProduct(int id, boolean retriveAssociation) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Product searchOnName(String name, boolean retriveAssociation) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int insert(Product dept) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Product dept) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int delete(Product dept) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	private ArrayList<Product> miscWhere(String wClause, boolean retrieveAssociation)
	{
            ResultSet results;
	    ArrayList<Product> list = new ArrayList<>();	
		
	    String query =  buildQuery(wClause);
  
            try{ // read the employee from the database
		Statement stmt = con.createStatement();
	 	stmt.setQueryTimeout(5);
	 	results = stmt.executeQuery(query);
	 	
	
		while( results.next() ){
	     	 Product pObj = new Product();
		 pObj = buildProduct(results);	
                 list.add(pObj);	
		}//end while
                 stmt.close();     
                 
			
		}//slut try	
	 	catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return list;
	}
	
	private String buildQuery(String wClause)
	{
	    String query="select id, NAME, PURCHASEPRICE, SALESPRICE, RENTPRICE, COUNTYOFORIGIN, MINSTOCK, CURRENTSTOCK FROM Product";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	
	private Product buildProduct(ResultSet results)
    {   Product pObj = new Product();
        try{ // the columns from the table emplayee  are used
        	pObj.setId(results.getString("id"));
        	pObj.setName(results.getString("NAME"));
        	pObj.setPurchasePrice(results.getDouble("purchaseprice"));
        	pObj.setSalesPrice(results.getDouble("salesprice"));
        	pObj.setRentPrice(results.getDouble("rentprice"));
        	pObj.setCountyOfOrigin(results.getString("countyoforigin"));
        	pObj.setMinStock(results.getInt("minstock"));
        	pObj.setCurrentStock(results.getInt("currentstock"));
              
        }
       catch(Exception e)
       {
           System.err.println("error in building the product object");
       }
       return pObj;
    }

	
	

}
